package com.bsj.sipgateway.web.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bsj.power.common.config.exception.ApiException;
import com.bsj.power.common.config.global.JsonResult;
import com.bsj.power.common.config.global.JsonResultEnum;
import com.bsj.power.common.config.global.TokenUser;
import com.bsj.power.common.config.redis.RedisConstant;
import com.bsj.power.common.def.DeviceAddDTO;
import com.bsj.power.common.def.dto.Device2DDTO;
import com.bsj.power.common.def.dto.DeviceLightDTO;
import com.bsj.power.common.def.dto.RedisDeviceInfo;
import com.bsj.power.common.def.dto.alarmReport.SceneFaultDTO;
import com.bsj.power.common.def.entity.PrepareDevice;
import com.bsj.power.common.def.entity.Scene;
import com.bsj.power.common.def.entity.gb28181.Device;
import com.bsj.power.common.def.entity.gb28181.DeviceChannel;
import com.bsj.power.common.def.entity.log.VideoOpLog;
import com.bsj.power.common.def.enums.VideoOpTypeEnum;
import com.bsj.power.common.def.vo.*;
import com.bsj.power.common.mapper.DeviceChannelMapper;
import com.bsj.power.common.mapper.DeviceMapper;
import com.bsj.power.common.mapper.SceneMapper;
import com.bsj.power.common.mapper.VideoOpLogMapper;
import com.bsj.power.common.util.DateUtils;
import com.bsj.power.common.util.ExceptionUtil;
import com.bsj.power.common.util.StpLoginUserUtil;
import com.bsj.power.common.util.StringUtils;
import com.bsj.sipgateway.cache.DeviceCache;
import com.bsj.sipgateway.common.constant.Constants;
import com.bsj.sipgateway.util.RedisDeviceInfoUtil;
import com.bsj.sipgateway.web.service.IDeviceService;
import com.github.pagehelper.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import redis.clients.bsj.JedisClusterBSJ;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description
 * @Author zhaoyang
 * @Date 2024/6/20 9:48
 */
@Slf4j
@Service("deviceServiceImpl")
public class DeviceServiceImpl implements IDeviceService {

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private SceneMapper sceneMapper;

    @Resource
    private VideoOpLogMapper videoOpLogMapper;

    @Autowired
    private JedisClusterBSJ jedisClusterBSJ;

    @Autowired
    private RedisDeviceInfoUtil redisDeviceInfoUtil;

    @Autowired
    private DeviceChannelMapper deviceChannelMapper;

    @Override
    public Long findIdByDeviceId(String deviceId) {
        return deviceMapper.selectIdByDeviceId(deviceId);
    }

    @Override
    public void updateDeviceOnline(boolean flag, Long id) {
        deviceMapper.updateOnline(flag, id);
    }

    @Override
    public boolean deviceIdisExist(String deviceId) {
        Long id = deviceMapper.selectIdByDeviceId(deviceId);
        return id != null;
    }

    @Override
    public boolean nickNameIsExist(String nickName) {
        QueryWrapper<Device> wrapper = new QueryWrapper<>();
        wrapper.eq("nick_name", nickName);
        Device device = deviceMapper.selectOne(wrapper);
        return device != null;
    }

    @Override
    public int addDevice(DeviceAddDTO dto) {
        String date = DateUtils.dateToStr(new Date());
        Device device = new Device();
        device.setDeviceId(dto.getDeviceId());
        device.setSceneId(dto.getSceneId());
        device.setNickName(dto.getNickName());
        device.setCameraType(dto.getCameraType());
        device.setPointJson(dto.getPointJson());
        device.setRoomNo(dto.getRoomNo());

        // 新增摄像头，设备通道默认是1个
        device.setChannelNumber(1);

        device.setCreateTime(date);
        device.setUpdateTime(date);
        // 设备参数赋予默认值（亮度对比度饱和度分辨路）
        device.setResolution(6);
        device.setBrightness(2);
        device.setContrast(2);
        device.setSaturation(2);

        int flag = deviceMapper.insert(device);
        if (flag > 0) {
            try {
                TokenUser tokenInfo = StpLoginUserUtil.getTokenUser();
                if (tokenInfo != null) {
                    VideoOpLog videoOpLog = new VideoOpLog();
                    int type = VideoOpTypeEnum.ADD.getOpType();
                    videoOpLog.setDeviceId(device.getDeviceId());
                    videoOpLog.setName(VideoOpTypeEnum.getByValue(type));
                    videoOpLog.setOpUserId(tokenInfo.getUserId());
                    videoOpLog.setOpUserName(tokenInfo.getUserName());
                    videoOpLog.setOpType(type);
                    videoOpLog.setOpTime(new Date());
                    videoOpLog.setContent("新增加的设备信息：设备国标id=" + device.getDeviceId()
                            + "，设备名称是=" + device.getNickName() + "，摄像头类型是=" + getCameraTypeByCode(device.getCameraType()));
                    videoOpLog.setNickName(device.getNickName());
                    videoOpLogMapper.insert(videoOpLog);
                }
            } catch (Exception e) {
                log.error("记录日志失败：{}", ExceptionUtil.getStackStr(e));
            }
        }
        return flag;
    }

    private String getCameraTypeByCode(Integer CameraTypeCode) {
        if (CameraTypeCode == 1) {
            return "球形摄像头";
        }
        if (CameraTypeCode == 2) {
            return "AI球形摄像头";
        }
        if (CameraTypeCode == 3) {
            return "网络摄像头";
        }
        if (CameraTypeCode == 4) {
            return "防爆球形摄像头";
        }
        return "";

    }

    private String getSettingContent(Device device, Device deviceInDb) {
        StringBuilder sb = new StringBuilder();
        if (!ObjectUtils.isEmpty(device.getResolution()) && !device.getResolution().equals(deviceInDb.getResolution())) {
            sb.append("分辨率由：").append(getResolutionStrByCode(deviceInDb.getResolution())).append("改为：")
                    .append(getResolutionStrByCode(device.getResolution())).append("，");
        }
        if (!ObjectUtils.isEmpty(device.getBrightness()) && !device.getBrightness().equals(deviceInDb.getBrightness())) {
            sb.append("亮度由：").append(getBrightnessStrByCode(deviceInDb.getBrightness())).append("改为：")
                    .append(getBrightnessStrByCode(device.getBrightness())).append("，");
        }
        if (!ObjectUtils.isEmpty(device.getContrast()) && !device.getContrast().equals(deviceInDb.getContrast())) {
            sb.append("对比度由：").append(getContrastStr(deviceInDb.getContrast())).append("改为：")
                    .append(getContrastStr(device.getContrast())).append("，");
        }
        if (!ObjectUtils.isEmpty(device.getSaturation()) && !device.getSaturation().equals(deviceInDb.getSaturation())) {
            sb.append("饱和度由：").append(getSaturationStr(deviceInDb.getSaturation())).append("改为：")
                    .append(getSaturationStr(device.getSaturation()));
        }
        return sb.toString();
    }

    private String getSaturationStr(Integer saturation) {
        if (saturation == null) {
            return "--";
        } else if (saturation == 1) {
            return "低";
        } else if (saturation == 2) {
            return "中";
        } else if (saturation == 3) {
            return "高";
        }
        return null;
    }

    private String getContrastStr(Integer contrast) {
        if (contrast == null) {
            return "--";
        } else if (contrast == 1) {
            return "低";
        } else if (contrast == 2) {
            return "中";
        } else if (contrast == 3) {
            return "高";
        }
        return null;

    }

    private String getBrightnessStrByCode(Integer brightness) {
        if (brightness == null) {
            return "--";
        } else if (brightness == 1) {
            return "低";
        } else if (brightness == 2) {
            return "中";
        } else if (brightness == 3) {
            return "高";
        }
        return null;
    }

    private String getResolutionStrByCode(Integer resolution) {
        if (resolution == null) {
            return "--";
        } else if (resolution == 1) {
            return "QCIF";
        } else if (resolution == 2) {
            return "CIF";
        } else if (resolution == 3) {
            return "4CIF";
        } else if (resolution == 4) {
            return "D1";
        } else if (resolution == 5) {
            return "720P";
        } else if (resolution == 6) {
            return "1080P/I";
        }
        return null;
    }

    private String getUpdateContent(Device device, Device deviceInDb) {
        StringBuilder sb = new StringBuilder();
        if (!ObjectUtils.isEmpty(device.getModel()) && !device.getModel().equals(deviceInDb.getModel())) {
            sb.append("型号由：").append(deviceInDb.getModel()).append("改为：").append(device.getModel()).append("，");
        }
        if (!ObjectUtils.isEmpty(device.getManufacturer()) && !device.getManufacturer().equals(deviceInDb.getManufacturer())) {
            sb.append("厂商由：").append(deviceInDb.getManufacturer()).append("改为：").append(device.getManufacturer()).append("，");
        }
        if (!ObjectUtils.isEmpty(device.getInstaller()) && !device.getInstaller().equals(deviceInDb.getInstaller())) {
            sb.append("安装人员由：").append(deviceInDb.getInstaller()).append("改为：").append(device.getInstaller()).append("，");
        }
        if (!ObjectUtils.isEmpty(device.getInstallerPhone()) && !device.getInstallerPhone().equals(deviceInDb.getInstallerPhone())) {
            sb.append("安装人员电话由：").append(deviceInDb.getInstallerPhone()).append("改为：").append(device.getInstallerPhone());
        }
        if (!ObjectUtils.isEmpty(device.getLocation()) && !device.getLocation().equals(deviceInDb.getLocation())) {
            sb.append("安装位置由：").append(deviceInDb.getLocation()).append("改为：").append(device.getLocation());
        }
        if (!ObjectUtils.isEmpty(device.getChannelNumber()) && !device.getChannelNumber().equals(deviceInDb.getChannelNumber())) {
            sb.append("摄像头路数由：").append(deviceInDb.getChannelNumber()).append("改为：").append(device.getChannelNumber());
        }
        if (!ObjectUtils.isEmpty(device.getSceneId()) && !device.getSceneId().equals(deviceInDb.getSceneId())) {
            Scene newScene = sceneMapper.selectById(device.getSceneId());
            Scene oldScene = sceneMapper.selectById(deviceInDb.getSceneId());
            sb.append("所属场景由：").append(oldScene.getSceneName()).append("改为：").append(newScene.getSceneName());
        }
        return sb.toString();

    }

    @Override
    public void updateDevice(Device device) {
        Device deviceInDb = deviceMapper.selectById(device.getId());
        if (deviceInDb == null) {
            log.warn("更新设备时未找到设备信息");
            return;
        }
        int type = VideoOpTypeEnum.UPDATE.getOpType();
        String content = "";
        if (!ObjectUtils.isEmpty(device.getResolution()) && !device.getResolution().equals(deviceInDb.getResolution())
                || !ObjectUtils.isEmpty(device.getBrightness()) && !device.getBrightness().equals(deviceInDb.getBrightness())
                || !ObjectUtils.isEmpty(device.getContrast()) && !device.getContrast().equals(deviceInDb.getContrast())
                || !ObjectUtils.isEmpty(device.getSaturation()) && !device.getSaturation().equals(deviceInDb.getSaturation())) {
            type = VideoOpTypeEnum.SETTING.getOpType();
            content = getSettingContent(device, deviceInDb);
        } else {
            content = getUpdateContent(device, deviceInDb);
        }


        // 父id为-1的场景不能绑定设备
        Integer sceneId = device.getSceneId();
        Scene scene = sceneMapper.selectById(sceneId);
        if (scene.getPid() != null && scene.getPid() == -1) {
            throw new ApiException(JsonResultEnum.PARAM_ERROR, "最上级场景：" + scene.getSceneName() + "不能绑定设备");
        }

        if (device.getDeviceId() != null) {
            QueryWrapper<Device> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("device_id", device.getDeviceId());
            Device deviceIdDevice = deviceMapper.selectOne(queryWrapper);
            if (deviceIdDevice != null && !deviceIdDevice.getId().equals(device.getId())) {
                // 说明设备编号被占用
                throw new ApiException(JsonResultEnum.NAME_IS_EXIST, "设备编号重复，请重新输入");
            } else {
                deviceInDb.setDeviceId(device.getDeviceId());
            }
        }
        if (device.getNickName() != null) {
            QueryWrapper<Device> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("nick_name", device.getNickName());
            Device nickNameDevice = deviceMapper.selectOne(queryWrapper);
            if (nickNameDevice != null && !nickNameDevice.getId().equals(device.getId())) {
                // 说明设备编号被占用
                throw new ApiException(JsonResultEnum.NAME_IS_EXIST, "设备名称重复，请重新输入");
            } else {
                deviceInDb.setNickName(device.getNickName());
            }
        }
        if (device.getManufacturer() != null) {
            deviceInDb.setManufacturer(device.getManufacturer());
        }
        if (device.getModel() != null) {
            deviceInDb.setModel(device.getModel());
        }
        if (device.getFirmware() != null) {
            deviceInDb.setFirmware(device.getFirmware());
        }
        if (!ObjectUtils.isEmpty(device.getTransport())) {
            deviceInDb.setTransport(device.getTransport());
        }
        if (!ObjectUtils.isEmpty(device.getHostAddress())) {
            deviceInDb.setHostAddress(device.getHostAddress());
        }
        if (!ObjectUtils.isEmpty(device.getStreamMode())) {
            deviceInDb.setStreamMode(device.getStreamMode());
        }
        if (!ObjectUtils.isEmpty(device.getChannelNumber())) {
            deviceInDb.setChannelNumber(device.getChannelNumber());
        }
        if (!ObjectUtils.isEmpty(device.getResolution())) {
            deviceInDb.setResolution(device.getResolution());
        }
        if (!ObjectUtils.isEmpty(device.getBrightness())) {
            deviceInDb.setBrightness(device.getBrightness());
        }
        if (!ObjectUtils.isEmpty(device.getContrast())) {
            deviceInDb.setContrast(device.getContrast());
        }
        if (!ObjectUtils.isEmpty(device.getSaturation())) {
            deviceInDb.setSaturation(device.getSaturation());
        }
        if (device.getInstaller() != null) {
            deviceInDb.setInstaller(device.getInstaller());
        }
        if (device.getInstallerPhone() != null) {
            deviceInDb.setInstallerPhone(device.getInstallerPhone());
        }
        if (device.getLocation() != null) {
            deviceInDb.setLocation(device.getLocation());
        }
        if (!ObjectUtils.isEmpty(device.getSceneId())) {
            deviceInDb.setSceneId(device.getSceneId());
        }
        if (device.getPointJson() != null) {
            deviceInDb.setPointJson(device.getPointJson());
        }
        if (!ObjectUtils.isEmpty(device.getCameraType())) {
            deviceInDb.setCameraType(device.getCameraType());
        }
        deviceInDb.setEquipmentNumber(device.getEquipmentNumber());
        deviceInDb.setUpdateTime(DateUtils.dateToStr(new Date()));
        deviceInDb.setRoomNo(device.getRoomNo());

        deviceMapper.updateById(deviceInDb);

        try {
            TokenUser tokenInfo = StpLoginUserUtil.getTokenUser();
            if (tokenInfo != null && !StringUtils.isEmpty(content)) {
                VideoOpLog videoOpLog = new VideoOpLog();
//                int type = VideoOpTypeEnum.UPDATE.getOpType();
                videoOpLog.setDeviceId(device.getDeviceId());
                videoOpLog.setName(VideoOpTypeEnum.getByValue(type));
                videoOpLog.setOpUserId(tokenInfo.getUserId());
                videoOpLog.setOpUserName(tokenInfo.getUserName());
                videoOpLog.setOpType(type);
                videoOpLog.setOpTime(new Date());
                videoOpLog.setContent(content);
                videoOpLog.setNickName(deviceInDb.getNickName());
                videoOpLogMapper.insert(videoOpLog);
            }
        } catch (Exception e) {
            log.error("记录日志失败：{}", ExceptionUtil.getStackStr(e));
        }
    }

    @Override
    public List<Device> selectDevicesByIds(List<Long> deviceIds) {
        return deviceMapper.selectBatchIds(deviceIds);
    }

    @Override
    public boolean delete(Integer did) {
        Device device = deviceMapper.selectById(did);
        if (device == null) {
            return true;
        }
//        DeviceCache.removeDevice(device.getDeviceId());

        jedisClusterBSJ.del(RedisConstant.REDIS_DEVICE_INFO + device.getDeviceId());
        jedisClusterBSJ.hdel(RedisConstant.DEVICE_REGISTER_MID_DTO, did + "");

        deviceMapper.deleteById(did);

        try {
            TokenUser tokenInfo = StpLoginUserUtil.getTokenUser();
            if (tokenInfo != null) {
                VideoOpLog videoOpLog = new VideoOpLog();
                int type = VideoOpTypeEnum.DELETE.getOpType();
                videoOpLog.setDeviceId(device.getDeviceId());
                videoOpLog.setName(VideoOpTypeEnum.getByValue(type));
                videoOpLog.setOpUserId(tokenInfo.getUserId());
                videoOpLog.setOpUserName(tokenInfo.getUserName());
                videoOpLog.setOpType(type);
                videoOpLog.setOpTime(new Date());
                videoOpLog.setContent("删除的设备编号是：" + device.getDeviceId() + "，摄像头类型是=" + getCameraTypeByCode(device.getCameraType()));
                videoOpLog.setNickName(device.getNickName());
                videoOpLogMapper.insert(videoOpLog);
            }
        } catch (Exception e) {
            log.error("记录日志失败：{}", ExceptionUtil.getStackStr(e));
        }

        return true;
    }

    @Override
    public Device selectById(Long did) {
        return deviceMapper.selectById(did);
    }

    @Override
    public IPage<Device> queryPageVideoDeviceList(Integer page, Integer size, String condition, String roomNo) {
        Page<Device> iPage = new Page<>(page, size);
        QueryWrapper<Device> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(roomNo)) {
            queryWrapper.eq("room_no", roomNo);
        }
        if (!StringUtils.isEmpty(condition)) {
            // 这里使用lambda的形式，避免or没有加括号导致查询不准确
            queryWrapper.and(wrapper -> {
                wrapper.like("nick_name", condition).or().like("device_id", condition);
            });
        }
        iPage = deviceMapper.selectPage(iPage, queryWrapper);
        return iPage;
    }

    @Override
    public Device selectByDeviceId(String deviceId) {
        return deviceMapper.getDeviceByDeviceId(deviceId);
    }

    @Override
    public List<Device> selectBySceneId(Integer sceneId) {
        QueryWrapper<Device> wrapper = new QueryWrapper<>();
        wrapper.eq("scene_id", sceneId);
        return deviceMapper.selectList(wrapper);
    }

    @Override
    public List<Device> selectBySceneIds(List<Integer> sceneIds) {
        return deviceMapper.selectBySceneIds(sceneIds);
    }

    @Override
    public List<Device> findDeviceByCondition(String condition) {
        QueryWrapper<Device> queryWrapper = null;
        if (!ObjectUtils.isEmpty(condition)) {
            queryWrapper = new QueryWrapper<>();
            queryWrapper.like("nick_name", condition).or().like("device_id", condition);
        }
        return deviceMapper.selectList(queryWrapper);
    }

    @Override
    public List<SceneFaultDTO> selectSceneFaultDTOByDeviceIds(List<String> deviceIds) {
        return deviceMapper.selectSceneFaultDTOByDeviceIds(deviceIds);
    }

    @Override
    public Long findAllDeviceCount() {
        return deviceMapper.selectCount(null);
    }

    @Override
    public List<Device> findAll() {
        return deviceMapper.selectList(null);
    }

    @Override
    public Device checkExist(String fieldName, Object fieldValue) {
        QueryWrapper<Device> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(fieldName, fieldValue);
        return deviceMapper.selectOne(queryWrapper);
    }

    @Override
    public void updateResolutionByDeviceId(Integer resolution, String deviceId) {
        deviceMapper.updateResolutionByDeviceId(resolution, deviceId);

    }

    @Override
    public List<Device> selectByDeviceIds(List<String> deviceIds) {
        QueryWrapper<Device> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("device_id", deviceIds);
        return deviceMapper.selectList(queryWrapper);
    }

    @Override
    public JsonResult deviceStatusStatistics() {
        List<String> deviceIds = deviceMapper.selectDeviceIds();
        int online = 0;
        int offline = 0;
        for (String deviceId : deviceIds) {
            boolean flag = redisDeviceInfoUtil.checkOnline(deviceId);
            if (flag) {
                online++;
            } else {
                offline++;
            }
        }

        DeviceStatusStatisticsVO vo = new DeviceStatusStatisticsVO();
        vo.setOnlineCount(online);
        vo.setOfflineCount(offline);
        vo.setTotalCount(deviceIds.size());
        JsonResult jsonResult = JsonResult.success();
        jsonResult.setData(vo);
        return jsonResult;
    }

    @Override
    public boolean updateDeviceLight(DeviceLightDTO deviceLightDTO) {
        if (deviceLightDTO.getResolution() == null
                && deviceLightDTO.getSaturation() == null
                && deviceLightDTO.getContrast() == null
                && deviceLightDTO.getBrightness() == null) {
            return true;
        }
        Device deviceInDb = deviceMapper.getDeviceByDeviceId(deviceLightDTO.getDeviceId());

        Device device = new Device();
        device.setDeviceId(deviceLightDTO.getDeviceId());
        device.setResolution(deviceLightDTO.getResolution());
        device.setSaturation(deviceLightDTO.getSaturation());
        device.setContrast(deviceLightDTO.getContrast());
        device.setBrightness(deviceLightDTO.getBrightness());
        deviceMapper.updateDeviceLight(device);

        int type = VideoOpTypeEnum.SETTING.getOpType();
        String content = "";
        if (!ObjectUtils.isEmpty(device.getResolution()) && !device.getResolution().equals(deviceInDb.getResolution())
                || !ObjectUtils.isEmpty(device.getBrightness()) && !device.getBrightness().equals(deviceInDb.getBrightness())
                || !ObjectUtils.isEmpty(device.getContrast()) && !device.getContrast().equals(deviceInDb.getContrast())
                || !ObjectUtils.isEmpty(device.getSaturation()) && !device.getSaturation().equals(deviceInDb.getSaturation())) {
            type = VideoOpTypeEnum.SETTING.getOpType();
            content = getSettingContent(device, deviceInDb);
        }

        try {
            TokenUser tokenInfo = StpLoginUserUtil.getTokenUser();
            if (tokenInfo != null && !StringUtils.isEmpty(content)) {
                VideoOpLog videoOpLog = new VideoOpLog();
//                int type = VideoOpTypeEnum.UPDATE.getOpType();
                videoOpLog.setDeviceId(device.getDeviceId());
                videoOpLog.setName(VideoOpTypeEnum.getByValue(type));
                videoOpLog.setOpUserId(tokenInfo.getUserId());
                videoOpLog.setOpUserName(tokenInfo.getUserName());
                videoOpLog.setOpType(type);
                videoOpLog.setOpTime(new Date());
                videoOpLog.setContent(content);
                videoOpLog.setNickName(deviceInDb.getNickName());
                videoOpLogMapper.insert(videoOpLog);
            }
        } catch (Exception e) {
            log.error("记录日志失败：{}", ExceptionUtil.getStackStr(e));
        }

        return true;
    }

    @Override
    public DeviceLightVO getDeviceLightVO(String deviceId) {
        DeviceLightVO deviceLightVO = deviceMapper.getDeviceLightVO(deviceId);
        if (deviceLightVO != null) {
            // 获取云台锁定状态（查缓存）
            String lockedStr = redisDeviceInfoUtil.getPtzControlLock(deviceLightVO.getDeviceId());
            if (!StringUtil.isEmpty(lockedStr)) {
                String[] s = lockedStr.split("_");
                deviceLightVO.setPtzControlLock(1); // 锁定
                deviceLightVO.setLockUid(Integer.parseInt(s[0]));
                deviceLightVO.setLockedUserWeight(Integer.parseInt(s[1]));
            } else {
                deviceLightVO.setPtzControlLock(0); // 未锁定
            }
        }
        return deviceLightVO;
    }

    @Override
    public JsonResult updateDevice2dInfo(List<Device2DDTO> device2DDTOS) {
        for (Device2DDTO device2DDTO : device2DDTOS) {
            Device device = new Device();
            Long id = device2DDTO.getId();
            String pointJson2d = device2DDTO.getPointJson2d();
            Integer floor = device2DDTO.getFloor();
            Integer building = device2DDTO.getBuilding();
            device.setId(id);
            if (!ObjectUtils.isEmpty(pointJson2d)) {
                device.setPointJson2d(pointJson2d);
            }
            if (!ObjectUtils.isEmpty(floor)) {
                device.setFloor(floor);
            }
            if (!ObjectUtils.isEmpty(building)) {
                device.setBuilding(building);
            }
            deviceMapper.updateById(device);
        }
        return JsonResult.success();
    }

    @Override
    public JsonResult<TwoDDeviceInfoVO> listDevice2DInfo(Integer building, Integer floor) {
        QueryWrapper<Device> wrapper = new QueryWrapper<>();
        wrapper.eq("building", building);
        wrapper.eq("floor", floor);
        List<Device> devices = deviceMapper.selectList(wrapper);
        if (CollectionUtils.isEmpty(devices)) {
            JsonResult result = JsonResult.fail(JsonResultEnum.PARAM_ERROR, "没有查询到数据");
            return result;
        } else {
            List<String> deviceIds = devices.stream().map(Device::getDeviceId).collect(Collectors.toList());
            List<DeviceChannel> deviceChannels = deviceChannelMapper.queryAllByDeviceIds(deviceIds);
            Map<String, List<DeviceChannel>> deviceChannelMap = deviceChannels.stream().collect(Collectors.groupingBy(DeviceChannel::getDeviceId));

            List<Device2DInfoVO> deviceVOS = new ArrayList<>();
            for (Device device : devices) {
                Device2DInfoVO deviceVO = new Device2DInfoVO();
                BeanUtils.copyProperties(device, deviceVO);
                List<DeviceChannel> deviceChannelList = deviceChannelMap.get(device.getDeviceId());
                deviceVO.setDeviceChannels(deviceChannelList);
                String rdsInfo = jedisClusterBSJ.get(RedisConstant.REDIS_DEVICE_INFO + deviceVO.getDeviceId());
                if (!StringUtil.isEmpty(rdsInfo)) {
                    RedisDeviceInfo redisDeviceInfo = JSON.parseObject(rdsInfo, RedisDeviceInfo.class);
                    deviceVO.setOnline(redisDeviceInfo.getOnline());
                } else {
                    deviceVO.setOnline(Constants.DEVICE_OFFLINE);
                }
                deviceVOS.add(deviceVO);
            }

            List<Device2DInfoStatusVO> statusVOS = new ArrayList<>();
            Map<Integer, List<Device2DInfoVO>> map = deviceVOS.stream().collect(Collectors.groupingBy(Device2DInfoVO::getCameraType));
            for (Map.Entry<Integer, List<Device2DInfoVO>> entry : map.entrySet()) {
                Device2DInfoStatusVO statusVO = new Device2DInfoStatusVO();
                Integer key = entry.getKey();
                statusVO.setCameraType(key);
                List<Device2DInfoVO> value = entry.getValue();
                switch (key) { // 摄像头类型1球形摄像头2AI球形摄像头3网络摄像头4防爆球形摄像头
                    case 1:
                        statusVO.setCameraTypeName("球形摄像头");
                        break;
                    case 2:
                        statusVO.setCameraTypeName("AI球形摄像头");
                        break;
                    case 3:
                        statusVO.setCameraTypeName("网络摄像头");
                        break;
                    case 4:
                        statusVO.setCameraTypeName("防爆球形摄像头");
                        break;
                }
                List<Device2DInfoVO> onlineDevice = value.stream()
                        .filter(vo -> vo.getOnline() == Constants.DEVICE_ONLINE).collect(Collectors.toList());
                statusVO.setDeviceTotalCount(value.size());
                statusVO.setOnlineCount(onlineDevice.size());
                statusVO.setOfflineCount(value.size() - onlineDevice.size());
                statusVOS.add(statusVO);
            }
            JsonResult jsonResult = JsonResult.success();
            TwoDDeviceInfoVO twoDDeviceInfoVO = new TwoDDeviceInfoVO();
            twoDDeviceInfoVO.setDevice2DInfoVOS(deviceVOS);
            twoDDeviceInfoVO.setDevice2DInfoStatusVOS(statusVOS);
            jsonResult.setData(twoDDeviceInfoVO);
            return jsonResult;
        }
    }

    @Override
    public JsonResult deleteDevice2dInfo(List<Long> longs) {
        int count = deviceMapper.updateDevice2dInfo(longs);
        if (count > 0) {
            return JsonResult.success();
        }
        return JsonResult.fail();
    }

    @Override
    public List<Device> selectDevicesByBuilding(int i) {
        QueryWrapper<Device> wrapper = new QueryWrapper<>();
        wrapper.eq("building", i);
        return deviceMapper.selectList(wrapper);
    }

    @Override
    public Integer selectResolutionByDeviceId(String deviceId) {
        return deviceMapper.selectResolutionByDeviceId(deviceId);

    }

    @Override
    public void updateIpAndPortByDeviceId(Device device) {
        deviceMapper.updateIpAndPortByDeviceId(device);
    }

    @Override
    public JsonResult addPrepareDevice(String deviceId) {
        PrepareDevice prepareDevice = deviceMapper.selectPrepareDeviceByDeviceId(deviceId);
        if (prepareDevice != null) {
            return JsonResult.fail(JsonResultEnum.DEVICE_ID_EXIST);
        }
        int count = deviceMapper.addPrepareDevice(deviceId);
        if (count > 0) {
            return JsonResult.success();
        }
        return JsonResult.fail();
    }

    @Override
    public JsonResult deletePrepareDevice(Integer id) {
        deviceMapper.deletePrepareDeviceById(id);
        return JsonResult.success();
    }

    @Override
    public JsonResult listPrepareDevice(Integer pageNumber, Integer pageSize, String condition) {
        int totalCount = deviceMapper.listPrepareDeviceCount(condition);
        int beginIndex = (pageNumber - 1) * pageSize;
        List<PrepareDevice> prepareDevices = deviceMapper.listPrepareDevice(beginIndex, pageSize, condition);
        JsonResult jsonResult = JsonResult.success();
        jsonResult.setTotal(totalCount);
        jsonResult.setData(prepareDevices);
        return jsonResult;
    }



    private String getResolution(Integer resolution) {
        // 分辨率(1:QCIF,2:CIF,3:4CIF,4:D1,5:720P,6:1080P/I)
        if (resolution == 1) {
            return "QCIF";
        } else if (resolution == 2) {
            return "CIF";
        } else if (resolution == 3) {
            return "4CIF";
        } else if (resolution == 4) {
            return "D1";
        } else if (resolution == 5) {
            return "720P";
        } else if (resolution == 6) {
            return "1080P";
        }
        return "";
    }

    private String getBrightness(Integer brightness) {
        if (brightness == 1) {
            return "低";
        } else if (brightness == 2) {
            return "中";
        } else if (brightness == 3) {
            return "高";
        }
        return "";
    }


}
